package com.example.yskjproject.ui.activity;


import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.example.yskjproject.R;
import com.example.yskjproject.base.BaseActivity;
import com.example.yskjproject.content.EventContent;
import com.example.yskjproject.databinding.ActivityWxBindBinding;
import com.example.yskjproject.event.EventMessage;
import com.example.yskjproject.http.APIService;
import com.example.yskjproject.http.Urls;
import com.example.yskjproject.http.callback.JsonCallback;
import com.example.yskjproject.model.LzyResponse;
import com.example.yskjproject.model.QRBindWxModel;
import com.example.yskjproject.model.WxScanCodeModel;
import com.example.yskjproject.utils.EventBusUtil;
import com.example.yskjproject.utils.Log;
import com.example.yskjproject.utils.SpCashUtils;
import com.example.yskjproject.view.dialog.WXCodeDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.tencent.qcloud.tuicore.util.ToastUtil;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class WechatBindActivity extends BaseActivity<ActivityWxBindBinding> {
    private ActivityWxBindBinding mActivityWxBindBinding;
    private Gson gson = new Gson();
    @Override
    protected ActivityWxBindBinding getViewBinding() {
        mActivityWxBindBinding = ActivityWxBindBinding.inflate(LayoutInflater.from(this));
        return mActivityWxBindBinding;
    }

    @Override
    protected void initData() {
        setTitle("微信号绑定");
        getWxCodeDate();
    }

    private void getWxCodeDate() {
        Type type = new TypeToken<LzyResponse<WxScanCodeModel>>() {
        }.getType();
        APIService.<LzyResponse<WxScanCodeModel>>getData(type, Urls.WX_CODE).subscribeOn(Schedulers.io()).map(response -> response.data).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<WxScanCodeModel>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(WxScanCodeModel wxScanCodeModel) {
                if (TextUtils.isEmpty(wxScanCodeModel.getImg_url())) {
                    return;
                }
                Glide.with(WechatBindActivity.this).load(wxScanCodeModel.getImg_url())
                        .apply(RequestOptions.bitmapTransform(new RoundedCorners(40)))//圆角半径
                        .into(mActivityWxBindBinding.imgCode);
                SpCashUtils.getInstance().setTicket(wxScanCodeModel.getTicket());

                setHandler();

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();            //请求失败
                Log.e("onError ： " + "获取二维码失败");
            }

            @Override
            public void onComplete() {

            }
        }); //
    }

    private void setHandler() {
        if (mHandler != null) {
            mHandler.removeMessages(1);
            mHandler.sendEmptyMessage(1);
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                Map<String, String> jsonParams = new HashMap<>();
                jsonParams.put("ticket", SpCashUtils.getInstance().getTicket());
                jsonParams.put("device_token", SpCashUtils.getInstance().getDeviceToken());
                String paramsDate = gson.toJson(jsonParams);
                RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), paramsDate);
                OkGo.<LzyResponse<QRBindWxModel>>post(Urls.LOOP_WX_USER).upRequestBody(requestBody).execute(new JsonCallback<LzyResponse<QRBindWxModel>>() {
                    @SuppressLint("SimpleDateFormat")
                    @Override
                    public void onSuccess(Response<LzyResponse<QRBindWxModel>> response) {
                        QRBindWxModel wxLoginModel = response.body().data;
                        if (wxLoginModel != null) {
                            switch (wxLoginModel.getBind_state()) {
                                case 0://未扫码
                                    mHandler.removeMessages(1);
                                    //间隔时间
                                    mHandler.sendEmptyMessageDelayed(1, 5000);
                                    break;
                                case 1://成功  直接登录
                                    EventBusUtil.sendEvent(new EventMessage(EventContent.upDate_user));
                                    ToastUtil.toastShortMessage("微信绑定成功");
                                    finish();
                                    break;

                            }
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse<QRBindWxModel>> response) {
                        super.onError(response);
                    }
                });

            }
        }
    };
}
